// pages/store-map/store-map.js
import mode from "../../utils/mode.js"


Page({

  /**
   * 页面的初始数据
   */
  data: {
    peopoNum:'0',
    userInfo:{},  //用户信息
    night:false,
    cityStore:[],  //当前城市门店列表
    choseStore:{},  //选择的门店
    city:'',   //选择的城市
    mainActiveIndex: 0,
    activeId: null,
    show:false,
    nowCity:{},   //定位信息
    nowTime:"",  //当前时间   时分
    choseDay:{},//选择日期
    week:[],   //本周日期
    weekList:['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],   //本周日期
    isOpen:true, //项目是否展开
    haveStore:0,    //所在城市是否有门店
    testList:[],//门店项目列表
    chosetest:{},  //选择的门店项目
    PMtime:[],//下午时间段
    AMtime:[],//上午时间段
    flag: false,
    height: '',
    navHeight: '',
    citys:[],   //获取有门店的所有城市
  },
  getCurrentTime(){ //获取当前时间
    const date = new Date()
    let h = date.getHours()
    h = this.addDate0(h);	//给为单数的月份补零
    let m = date.getMinutes()
    m = this.addDate0(m);	//给为单数的月份补零
    let now = h+':'+m
    this.setData({
      nowTime:now
    })
  },
  onClose() {
    this.setData({ show: false });
  },
  getCitys(){   //获取有门店的所有城市
    var that = this
    wx.$api.getcity().then(res=>{
          if(res.code>0){
            let resData = res.data
            let now = that.data.nowCity
            let index = resData.indexOf(now.city)
            if(now.city&&index>-1){
              that.setData({
                haveStore:1
              })
            }else{
              that.setData({
                haveStore:-1
              })
            }
            that.setData({
              citys: resData,
            })
            that.getStores()
          }else{
            wx.showToast({
              title: res.msg,
              icon:'none'
            })
          }
            
    })
  },
  open(){  //展示城市  门店
    this.setData({
      show:true
    })
  },
  goTestInfo(e){   //去项目详情页
    let timeItem = e.currentTarget.dataset.item
    let info = {
      id:this.data.chosetest.id,
      time:timeItem.time,
      week:this.data.choseDay,
      storeId:this.data.choseStore.id
    }
    wx.navigateTo({
      url: '/pages/exclusive-details/exclusive-details?info='+JSON.stringify(info),
    })
  },
  setherght () {//动态获取导航栏高度
    let menuButtonObject = wx.getMenuButtonBoundingClientRect()
    // 动态获取导航栏高度
    wx.getSystemInfo({
      success: res => {
        console.log(res)
        let statusBarHeight = res.statusBarHeight,
          // navTop = menuButtonObject.top,//胶囊按钮与顶部的距离
          navHeight = menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2 //导航高度
        let screenWidths = res.screenWidth
        console.log(screenWidths)
        // this.globalData.windowHeight = res.windowHeight;
        this.setData({
          height: statusBarHeight,
          navHeight: navHeight,
          screenWidth: screenWidths
        })
      },
      fail (err) {
        console.log(err)
      }
    })

  },
  getTests(){   //获取门店项目
    var that = this
    wx.$api.getproject({
          store_id:that.data.choseStore.id,
          date:that.data.choseDay.date
        }).then(res=>{
          if(res.code>0){
            let resData = res.data
            if(resData.length>0){
              let item = resData[0]
              that.choseTest(item)
              that.setData({
                testList: resData
              })
            }else{
              that.setData({
                testList: [],
                AMtime:[],
                PMtime:[]
              })
            }
            
          }else{
            wx.showToast({
              title: res.msg,
              icon:'none'
            })
          }
    })
  },
  choseTest(e){   //选择项目
    let item = (e&&e.target?e.target.dataset.item:e)||[]
    let timeList=item.time_interva_nums||[]
    let AMtime=[]
    let PMtime=[]
    if(timeList.length>0){
      timeList.forEach((one)=>{
        let hour = one.time.slice(0,2)
        if(hour<12){
          AMtime.push(one)
        }else{
          PMtime.push(one)
        }
      })
    }
    this.setData({
      chosetest:item,
      AMtime:AMtime,
      PMtime:PMtime
    })
  },
  toChoseDay(e){   //选择日期
    let item = e.target.dataset.item||e.currentTarget.dataset.item
    if(item.status>0){
      this.setData({
        choseDay:item
      })
      this.getTests()
    }
  },
  openStoreList () {//打开门店列表
    wx.navigateTo({
      url: '../store/store',
    })
  },
  toOpen(){   //展开项目
    this.setData({
      isOpen:!this.data.isOpen
    })
  },
	getWeek() {   //返回最近七天的日期
		let days = [];
    const date = new Date()
    let day = date.getDay()
    for(let i=1; i<=7;i+=1){		//今天加上前6天
      let num = i-day
			let dateItem= new Date(date.getTime() + num * 24 * 60 * 60 * 1000);	//使用当天时间戳减去以前的时间毫秒（小时*分*秒*毫秒）
      let d= dateItem.getDate();	//获取日期
      let m = dateItem.getMonth()+1
      let y = dateItem.getFullYear()
      m = this.addDate0(m);	//给为单数的月份补零
      d = this.addDate0(d);	//给为单数的日期补零
      let allDate = y+'-'+m+'-'+d
      let dayItem={
        index:i,
        week:'周'+ (i==1?'一':i==2?'二':i==3?'三':i==4?'四':i==5?'五':i==6?'六':'日'),
        date:allDate,
        month:m,
        day:d,
        status:num>0?2:num==0?1:0
      }
      if(num==0){
        this.setData({
          choseDay:dayItem
        })
      }
			days.push(dayItem);	//添加至数组
    }
    this.setData({
      week:days
    })
	},
  getStores(){  //获取门店列表
    var that = this
    wx.$api.storeLists({
          city:that.data.choseCity||that.data.nowCity.city,
    }).then(res=>{
          if(res.code>0){
            let resData = res.data
            let item = resData.length>0?resData[0]:{}
            that.setData({
              choseStore:item,
              cityStore: resData
            })
            that.getTests()
          }else{
            wx.showToast({
              title: res.msg,
              icon:'none'
            })
          }
    })
  },
	//给日期加0
	addDate0(time) {
		if (time.toString().length == 1) {
			time = '0' + time.toString();
		}
		return time;
  },
  toChoseStore(e){  //选择门店
    let store = e.currentTarget.dataset.item
    this.getTests()
    this.setData({
      choseStore:store,
      show:false
    })
  },
  toChoseCity(e){  //选择城市
    let city = e.currentTarget.dataset.item
    this.setData({
      choseCity:city
    })
    this.getStores()
  },
  getflag () {
    if(this.data.userInfo&&this.data.userInfo.id){
      // this.getLocation()
      if(this.data.userInfo.store_expecta_status>0){
        this.getNum('上海市','上海市')
      }else{
        this.addNum('上海市','上海市')
      }
    }else{
      wx.navigateTo({
        url: '/pages/register/register',
      })
    }
    
    // this.setData({
    //   flag: true
    // })
    // wx.setStorage({
    //   key:'showCity',
    //   data:true
    // })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getWeek()
    this.setherght()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  
  hasNight: function (hour) {
    return hour > 18 || hour < 7
  },
  setTabbar(){
    let night = this.hasNight(new Date().getHours())
    this.setData({
      night: night,
    })
    if (night) {
      wx.setTabBarStyle({
        color: '#AAA',
        selectedColor: '#fff',
        backgroundColor: '#000',
        borderStyle: "black",
      })
      wx.setTabBarItem({
        index: 0,
        selectedIconPath: "/image/navbar/1-1.png",
      }
      )
      wx.setTabBarItem({
        index: 1,
        selectedIconPath: "/image/navbar/2-1.png",
      })
      wx.setTabBarItem({
        index: 2,
        selectedIconPath: "/image/navbar/3-1.png",
      })
      wx.setTabBarItem({
        index: 3,
        selectedIconPath: "/image/navbar/4-1.png",
      })
    } else {
      wx.setTabBarStyle({
        color: '#AAA',
        selectedColor: '#000',
        backgroundColor: '#fff',
        borderStyle: "white",
      })
      wx.setTabBarItem({
        index: 0,
        selectedIconPath: "/image/navbar/1-3.png"
      }
      )
      wx.setTabBarItem({
        index: 1,
        selectedIconPath: "/image/navbar/2-3.png"
      })
      wx.setTabBarItem({
        index: 2,
        selectedIconPath: "/image/navbar/3-3.png"
      })
      wx.setTabBarItem({
        index: 3,
        selectedIconPath: "/image/navbar/4-3.png"
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // let area = wx.getStorageSync("nowCity")
    // if(area&&area.city){
    //   this.setData({
    //     nowCity:area,
    //     choseCity:area.city
    //   })
    //   this.getCitys()
    // }else{
    //   this.getLocation()
    // }

    var uinfo = wx.getStorageSync('uinfo') || null
    if (uinfo && uinfo.user) {
        this.setData({
          userInfo:uinfo.user
        })
        if(uinfo.user.store_expecta_status>0){
          // this.getLocation()
          this.getNum('上海市','上海市',1)
          this.setData({
            flag:true,
            haveStore:0
          })
        }else{
          this.setData({
            flag:false,
            haveStore:-1
          })
        }
    }else{
      this.setData({
        haveStore:-1
      })
    }


    
    this.setTabbar()

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    let isClick = wx.getStorageSync('showCity')||false
    this.setData({
      flag: isClick
    })

    this.getCurrentTime()
    setInterval(() => {
      this.getCurrentTime()
    }, 30000);
    
  },
//   getLocation() {//获取定位
//       let that = this
//       wx.getLocation({
//         type:'wgs84',
//         altitude: 'true',
//         success (res) {
//           let data = {
//             lat: res.latitude,
//             lng: res.longitude
//           }
//           mode.itemText(data).then(e => {
//             if(e.code>0){
//               let area={
//                 lat: res.latitude,
//                 lng: res.longitude,
//                 province:e.data.province,
//                 city:e.data.city,
//                 area:e.data.area,
//               }
//               if(that.data.userInfo.store_expecta_status>0){
//                 that.getNum(e.data.province,e.data.city)
//               }else{
//                 that.addNum(e.data.province,e.data.city)
//               }
              
//               // wx.setStorage({
//               //   key: 'nowCity',
//               //   data: area,
//               // });
//               // that.setData({
//               //   nowCity:area,
//               //   choseCity:e.data.city
//               // })
//             //  that.getCitys()
//             }else{
//               wx.showToast({
//                 title: e.msg,
//                 icon:"none"
//               })
//             }
//           })
//         },
//         fail (res) {
//           that.setData({
//             haveStore:-1
//           })
//         }
//       })
//     },
  addNum(pp,cc){ //新增点亮人数
    var that = this
    wx.$api.storeExceptionAdd({
          user_id:that.data.userInfo.id,
          province:pp,
          city:cc
        }).then(res=>{
          if(res.code>0){
            that.getNum(pp,cc)
          }else{
            that.getNum(pp,cc)
            wx.showToast({
              title: res.msg,
              icon:'none'
            })
          }
    })
  },
  getNum(pp,cc,i){  //获取当地点亮人数
    var that = this
    wx.$api.storeExceptionGetinfo({
          province:pp,
          city:cc
        }).then(res=>{
          if(res.code>0){
            that.setData({
              peopoNum: res.data,
              flag:true,
              haveStore:-1
            })
          }else{
            that.setData({
              peopoNum: '0',
              flag:false,
              haveStore:-1
            })
            wx.showToast({
              title: res.msg,
              icon:'none'
            })
          }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.setStorage({ key: 'isFrom', data: '/pages/store-map/store-map' })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})